package com.yxy.utils;

import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.yxy.exception.FileUploadException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;


//交给IOC容器管理
@Component
@Slf4j
public class QiniuOSSUtil {

    private static final String accessKey = "XCZJwAEQ7EFWXSFuJodD89f16ntImTuRwJjk-PPA";

    private static final String accessSecretKey = "siQJC3VlnRz-AJNm4axObW2OqDdK9d31I8N0I_Ie";

    private static final String bucket = "pear-cos";

    /**
     * 上传文件到七牛云对象存储
     * @param file
     * @param fileName
     * @return
     */
    private static boolean uploadFile(MultipartFile file, String fileName){
        // 构造一个带指定Region对象的配置类
        // 最开始配置的是自动获取区域Region.autoRegion() 报了java.net.UnknownHostException: upload-z2.qiniup.com on错误
        // 后面确认存储区域后取消自动获取，改为对应的区域region2()
        /*
          解决出处：https://www.cnblogs.com/liftsail/p/16944399.html
          存储区域
          华东机房(region0): up.qiniup.com 或 upload.qiniup.com
          华北机房(region1): up-z1.qiniup.com 或 upload-z1.qiniup.com
          华南机房(region2): up-z2.qiniup.com 或 upload-z2.qiniup.com
          北美机房(regionNa0): up-na0.qiniup.com 或 upload-na0.qiniup.com
          新加坡机房(regionAs0): up-as0.qiniup.com 或 upload-as0.qiniup.com
          雾存储华东一区(regionFogCnEast1): up-fog-cn-east-1.qiniup.com 或 upload-fog-cn-east-1.qiniup.com
         */
        Configuration cfg = new Configuration(Region.region2());

        UploadManager uploadManager = new UploadManager(cfg);
        // 默认不指定key的情况下会以文件内容的hash值作为文件名
        try {
            byte[] bytes = file.getBytes();
            Auth auth = Auth.create(accessKey, accessSecretKey);
            String upToken = auth.uploadToken(bucket);
            Response response = uploadManager.put(bytes, "bfbbs/" + fileName, upToken);
            // 打印日志
            log.info("上传结果：{}", response.bodyString());
            return true;
        } catch (IOException e) {
            throw new FileUploadException(e.getMessage());
        }
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    public static String uploadToQiniu(MultipartFile file){
        // 访问域名
        String domain = "http://cdn.ymvpear.icu/bfbbs/";
        // 获取文件名
        String originalFilename = file.getOriginalFilename();
        // 获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        String fileName = UUID.randomUUID().toString() + "." + suffix;

        boolean flag = uploadFile(file, fileName);
        return flag ? domain + fileName : null;
    }
}
